package com.kikt.closeappdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

/**
 * Created by kikt on 2016/1/9.
 * 一个监听后台的广播接收者
 */
public class BackgroundReceiver extends BroadcastReceiver {

    private BackgroundListener listener;

    public BackgroundReceiver(BackgroundListener listener) {
        this.listener = listener;
    }

    String SYSTEM_REASON = "reason";
    String SYSTEM_HOME_KEY = "homekey";
    String SYSTEM_HOME_KEY_LONG = "recentapps";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra(SYSTEM_REASON);
            if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                //表示按了home键,程序到了后台
                if (listener != null) {
                    listener.onDesktop();
                }
            }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){
                //表示长按home键,显示最近使用的程序列表
                if (listener != null) {
                    listener.onChangeApp();
                }
            }
        }
    }

    /**
     * 后台监听
     */
    public interface BackgroundListener {
        void onDesktop();
        void onChangeApp();
    }
}
